package com.magic.gre.ui.activity;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.widget.TextView;

import com.bigkoo.pickerview.builder.TimePickerBuilder;
import com.bigkoo.pickerview.listener.OnTimeSelectListener;
import com.bigkoo.pickerview.view.TimePickerView;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.magic.gre.R;
import com.magic.gre.base.activity.BaseMVPActivity;
import com.magic.gre.entity.SexBean;
import com.magic.gre.entity.UserBean;
import com.magic.gre.entity.base.BaseWheelIm;
import com.magic.gre.helper.DialogHelper;
import com.magic.gre.mvp.contract.ModifyPerContract;
import com.magic.gre.mvp.presenter.ModifyPerpresenterImpl;
import com.magic.gre.ui.dialog.BirthDialog;
import com.magic.gre.ui.dialog.ChoosePicDialog;
import com.magic.gre.ui.dialog.MultipleBottomDialog;
import com.magic.gre.utils.PermissonUtils;
import com.noname.lib_base_java.entity.FielBean;
import com.noname.lib_base_java.entity.MsgEvent;
import com.noname.lib_base_java.entity.NetFielBean;
import com.noname.lib_base_java.glide.LoadImageUtils;
import com.noname.lib_base_java.net.RxBus;
import com.noname.lib_base_java.util.PathUtil;
import com.noname.lib_base_java.util.TimeUtils;
import com.noname.lib_base_java.util.ToastUtil;
import com.tbruyelle.rxpermissions2.RxPermissions;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.gavinliu.android.lib.shapedimageview.ShapedImageView;
import io.reactivex.functions.Consumer;

/**
 * Author: Lmoumou
 * Date: 2019-01-11 10:31
 * 文件名: ModifyPerActivity
 * 描述:
 */
public class ModifyPerActivity extends BaseMVPActivity<ModifyPerpresenterImpl> implements ModifyPerContract.View,
        ChoosePicDialog.OnChooseDialogListener {

    @BindView(R.id.nick_tv)
    TextView nickTv;
    @BindView(R.id.phone_tv)
    TextView phoneTv;
    @BindView(R.id.sex_tv)
    TextView sexTv;
    @BindView(R.id.head_iv)
    ShapedImageView headIv;
    @BindView(R.id.email_tv)
    TextView emailTv;
    @BindView(R.id.birthday_tv)
    TextView birthdayTv;

    public static void startThis(Context context) {
        Intent intent = new Intent(context.getApplicationContext(), ModifyPerActivity.class);
        context.startActivity(intent);
    }

    private RxPermissions rxPermissions;
    private MultipleBottomDialog<SexBean> sexDialog;
    private List<BaseWheelIm> sexDataList = new ArrayList<>();
    private ChoosePicDialog picDialog;
    private HashMap<String, Object> parmsMap = new HashMap<>();
    private TimePickerView birthTime;

    @Override
    protected int getLayoutId() {
        return R.layout.activity_modify_per;
    }

    @Override
    protected ModifyPerpresenterImpl creatPresenter() {
        return new ModifyPerpresenterImpl(this);
    }

    @Override
    protected void netOverride() {

    }

    @Override
    protected void handlerMsg(MsgEvent msgEvent) {
        super.handlerMsg(msgEvent);
        switch (msgEvent.getEvent()) {
            case MsgEvent.MODIFY_NICK:
                String nick = (String) msgEvent.get("nick");
                if (!TextUtils.isEmpty(nick)) {
                    parmsMap.put("nickname", nick);
                }
                nickTv.setText(nick);
                break;
            case MsgEvent.MODIFY_PHONE:
                String phoneStr = (String) msgEvent.get("phone");
                phoneTv.setText(phoneStr);
                break;
            case MsgEvent.UPDATE_PER:
                mPresenter.pGetUserInfo();
                break;
        }
    }


    @Override
    protected void initView(@Nullable Bundle savedInstanceState) {
        super.initView(savedInstanceState);
        registerRxBus();

        sexDialog = new MultipleBottomDialog<>();
        sexDialog.setOnSelectListener(new MultipleBottomDialog.OnSelectListener<SexBean>() {
            @Override
            public void onSetect(SexBean selectBean, String tag, int position) {
                try {
                    int id = Integer.valueOf(tag);
                    TextView textView = findViewById(id);
                    textView.setText(selectBean.getSex());
                    textView.setTag(position);
                    if (id == R.id.sex_tv) {
                        parmsMap.put("gender", selectBean.getId());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });

        mPresenter.pGetUserInfo();
    }

    @OnClick(value = {R.id.nick_ll, R.id.phone_ll, R.id.pwsd_ll, R.id.sex_ll, R.id.head_ll, R.id.sumbit_bt,
            R.id.birthday_ll})
    protected void onClick(View view) {
        switch (view.getId()) {
            case R.id.nick_ll:
                ModifyNickActivity.startThis(this, String.valueOf(nickTv.getText()));
                break;
            case R.id.phone_ll:
                ModifyPhoneActivity.startThis(this);
                break;
            case R.id.pwsd_ll:
                SetModifyPwsdActivity.startThis(this);
                break;
            case R.id.sex_ll:
                DialogHelper.getSexData(sexDataList);
                showDialog(sexDialog, R.id.sex_tv, sexTv, sexDataList);
                break;
            case R.id.head_ll:
                showHeadDialog();
                break;
            case R.id.sumbit_bt:
                mPresenter.pChangeInfo(parmsMap);
                break;
            case R.id.birthday_ll:
                if (birthTime == null) {
                    initCustomOptionPicker();
                }
                birthTime.show();
                break;
        }
    }

    private void initCustomOptionPicker() {
        birthTime = new TimePickerBuilder(this, new OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                parmsMap.put("birth", TimeUtils.long2String(date.getTime(), TimeUtils.FORMAT_YMD_ONE));
                birthdayTv.setText(TimeUtils.long2String(date.getTime(), TimeUtils.FORMAT_YMD_ONE));
            }
        }).setGravity(Gravity.CENTER)
                .setTextColorCenter(ContextCompat.getColor(this,R.color.main_color))
                .setTextColorOut(ContextCompat.getColor(this,R.color.color_666666))
                .setCancelColor(ContextCompat.getColor(this,R.color.main_color))
                .setSubmitColor(ContextCompat.getColor(this,R.color.main_color))
                .setBgColor(ContextCompat.getColor(this,R.color.color_FFFFFF))
                .isCenterLabel(true)
                .build();
    }

    private void showHeadDialog() {
        if (picDialog == null) {
            picDialog = new ChoosePicDialog();
            picDialog.setOnChooseDialogListener(this);
        }
        picDialog.showThis(getSupportFragmentManager(), ChoosePicDialog.class.getSimpleName());
    }


    @Override
    public void vGetUserInfo(UserBean userBean) {
        updataInfo(userBean);
    }

    private void updataInfo(UserBean userBean) {
        LoadImageUtils.loadImage(PathUtil.imgPath(userBean.getPhoto()), headIv);
        phoneTv.setText(userBean.getPhone());
        emailTv.setText(userBean.getEmail());
        nickTv.setText(userBean.getNickname());
        if (userBean.getGender().equals("0")) {
            sexTv.setText("女");
        } else {
            sexTv.setText("男");
        }

        birthdayTv.setText(TimeUtils.long2String(userBean.getBirth(),TimeUtils.FORMAT_YMD_ONE));
    }

    @Override
    public void vChangInfo(UserBean userBean) {
        ToastUtil.getInstance().showNormal(this, "保存成功");

        updataInfo(userBean);

        RxBus.getInstance().post(new MsgEvent(MsgEvent.UPDATE_PER));
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK && (requestCode == 1 || requestCode == 2)) {
            String path = PictureSelector.obtainMultipleResult(data).get(0).getCompressPath();
            FielBean bean = new FielBean(path, true);
            List<FielBean> fielBeans = new ArrayList<>();
            fielBeans.add(bean);
            mPresenter.pUpLoadFiel(fielBeans);
        }

    }

    @SuppressLint("CheckResult")
    @Override
    public void onPhotograph() {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(PermissonUtils.READ_WRITE)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            PictureSelector.create(ModifyPerActivity.this)
                                    .openCamera(PictureMimeType.ofImage())
                                    .enableCrop(true)//是否裁剪
                                    .compress(true)//压缩
                                    .minimumCompressSize(500)
                                    .withAspectRatio(1, 1)
                                    .freeStyleCropEnabled(false)
                                    .circleDimmedLayer(false)
                                    .showCropFrame(false)
                                    .showCropGrid(false)
                                    .rotateEnabled(false)
                                    .scaleEnabled(true)
                                    .forResult(1);
                        } else {
                            ToastUtil.getInstance().showNormal(ModifyPerActivity.this, "权限获取失败");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    @SuppressLint("CheckResult")
    @Override
    public void onAlbum() {
        if (rxPermissions == null) {
            rxPermissions = new RxPermissions(this);
        }
        rxPermissions.request(PermissonUtils.PHOTOGRAPH)
                .subscribe(new Consumer<Boolean>() {
                    @Override
                    public void accept(Boolean aBoolean) throws Exception {
                        if (aBoolean) {
                            PictureSelector.create(ModifyPerActivity.this)
                                    .openGallery(PictureMimeType.ofImage())
                                    .maxSelectNum(1)
                                    .isGif(false)
                                    .selectionMode(PictureConfig.MULTIPLE)
                                    .imageSpanCount(3)
                                    .previewImage(false)
                                    .isCamera(true)
                                    .enableCrop(false)
                                    .compress(true)
                                    .withAspectRatio(1, 1)
                                    .freeStyleCropEnabled(false)
                                    .circleDimmedLayer(false)
                                    .showCropFrame(false)
                                    .showCropGrid(false)
                                    .rotateEnabled(false)
                                    .scaleEnabled(true)
                                    .forResult(2);
                        } else {
                            ToastUtil.getInstance().showNormal(ModifyPerActivity.this, "权限获取失败");
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {

                    }
                });
    }

    @Override
    public void upLoadFiels(List<NetFielBean> fielBeens) {
        super.upLoadFiels(fielBeens);
        if (fielBeens != null && !fielBeens.isEmpty()) {
            parmsMap.put("photo", fielBeens.get(0).getSourcePath());
            LoadImageUtils.loadImage(PathUtil.imgPath(fielBeens.get(0).getSourcePath()), headIv);
        }
    }
}
